<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    width="90%"
    :closeFunc="
      () => {
        $emit('success');
        return true;
      }
    "
  >
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1" tab="危险源辨识/隐患上报记录">
        <BasicTable
          @register="registerRecordTable"
          size="small"
          :columns="getUnitIdentifyRecordColumn"
          :loading="false"
          :ellipsis="true"
          :pagination="false"
          :data-source="tableData.identifys"
          :scroll="{ x: false, y: 'calc(100vh - 250px)' }"
          :key="unitid"
        >
          <template #toolbar>
            <a-button
              type="primary"
              v-if="mode == 'identify'"
              @click="onIdentifyButtonClick(null, null)"
              ><PlusOutlined />新增危险源辨识/上报隐患</a-button
            >
            <a-button @click="reIdentifyButtonClick">全面辨识</a-button>
          </template>
          <template #title="{ column, record }">
            <span @click="onViewHazardIdentifyButtonClick(record)">{{ record.title }}</span>
          </template>
          <template #identificationresult="{ column, record }">
            <Tag
              v-if="
                record.identificationresult !== null && record.identificationresult !== undefined
              "
              :color="
                identifyOptions.filter((item) => item.value == record.identificationresult)[0]
                  ?.color
              "
            >
              {{
                identifyOptions.filter((item) => item.value == record.identificationresult)[0]?.text
              }}</Tag
            >
            <span v-else></span>
          </template>
          <template #ismajor="{ column, record }">
            <div v-if="record.ismajor !== undefined">
              <a-tag v-if="record.ismajor == true" color="#cd201f">重大</a-tag>
              <a-tag v-else-if="record.ismajor == false" color="#3b5999">一般</a-tag>
            </div>
          </template>
          <template #confirmresult="{ column, record }">
            <Tag
              v-if="record.confirmresult !== null && record.confirmresult !== undefined"
              :color="
                identifyOptions.filter((item) => item.value == record.confirmresult)[0]?.color
              "
            >
              {{
                identifyOptions.filter((item) => item.value == record.confirmresult)[0]?.text
              }}</Tag
            >
            <span v-else></span>
          </template>
          <template #action="{ column, record, index }" v-if="mode == 'identify'">
            <TableAction
              v-if="!record.hasconfirm"
              :actions="[
                {
                  icon: 'ant-design:edit-outlined',
                  onClick: onEditRecordButtonClick.bind(null, record),
                },
                {
                  icon: 'ant-design:delete-outlined',
                  color: 'error',
                  popConfirm: {
                    title: '是否确认删除记录',
                    placement: 'left',
                    confirm: onDeleteRecordButtonClick.bind(null, record),
                  },
                },
              ]"
            />
            <TableAction
              v-else-if="record.identifyid && record.hasconfirm"
              :actions="[
                {
                  icon: 'ant-design:check-circle-outlined',
                  tooltip: '确认无变化',
                  color: 'success',
                  popConfirm: {
                    title: '是否确认无变化',
                    placement: 'left',
                    confirm: onNoChangeButtonClick.bind(null, record),
                  },
                },
                {
                  icon: 'ant-design:search-outlined',
                  tooltip: '重新辨识',
                  onClick: onIdentifyButtonClick.bind(null, record, null),
                },
              ]"
            />
          </template>
        </BasicTable>
      </a-tab-pane>
      <a-tab-pane key="2" tab="危险源台账">
        <BasicTable
          @register="registerLedgerTable"
          size="small"
          :columns="unitViewHazardColumn"
          :loading="false"
          :ellipsis="true"
          :pagination="false"
          :data-source="ledgerData"
          :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
          :key="unitid"
          @change="tableChange"
        >
          <template #ismajor="{ column, record }">
            <Tag v-if="record.ismajor" color="#cd201f">重大危险源</Tag>
            <Tag v-else color="#3b5999">一般危险源</Tag>
          </template>
          <template #identificationresult="{ column, record }">
            <Tag
              v-if="
                record.identificationresult !== null && record.identificationresult !== undefined
              "
              :color="
                identifyOptions.filter((item) => item.value == record.identificationresult)[0]
                  ?.color
              "
            >
              {{
                identifyOptions.filter((item) => item.value == record.identificationresult)[0]?.text
              }}</Tag
            >
            <span v-else>-</span>
          </template>
          <template #risklevel="{ column, record }">
            <Tag
              v-if="record.risklevel"
              :color="riskLevelOptions.filter((item) => item.value == record.risklevel)[0]?.color"
            >
              {{ riskLevelOptions.filter((item) => item.value == record.risklevel)[0]?.text }}</Tag
            >
            <span v-else>-</span>
          </template>
          <template
            #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
          >
            <!-- 表格筛选 -->
            <div style="padding: 8px">
              <a-input
                ref="searchInput"
                :value="selectedKeys[0]"
                style="width: 188px; margin-bottom: 8px; display: block"
                @change="(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
              />
              <a-button
                type="primary"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
              >
                筛选
              </a-button>
              <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
                重置
              </a-button>
            </div>
          </template>

          <template #action="{ column, record, index }" v-if="mode == 'identify'">
            <TableAction
              :actions="[
                {
                  icon: 'ant-design:check-circle-outlined',
                  tooltip: '确认无变化',
                  color: 'success',
                  popConfirm: {
                    title: '是否确认无变化',
                    placement: 'left',
                    confirm: onNoChangeButtonClick.bind(null, record),
                  },
                },
                {
                  icon: 'ant-design:search-outlined',
                  tooltip: '重新辨识',
                  onClick: onIdentifyButtonClick.bind(null, record, index),
                },
              ]"
            />
          </template>
        </BasicTable>
      </a-tab-pane>
    </a-tabs>
    <HazardIndentifyModal
      @register="registerHazardOperate"
      @success="opSuccess"
      :orgcode="orgcode"
    />
    <UpdateIdentifyRecord @register="registerUpdateIdentifyRecord" @success="opSuccess" />
    <HazardInfo @register="registerHazardLogs" />
    <IdentifyConfirmModal @register="registerHazardIdentifyInfo" />
  </BasicDrawer>
</template>

<script lang="ts">
  import {
    defineComponent,
    ref,
    unref,
    computed,
    watch,
    reactive,
    onMounted,
    createVNode,
  } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage, createInfoModal, createErrorModal } = useMessage();
  import { BasicTable, TableAction, useTable } from '/@/components/Table/index';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import {
    queryIdentifyRecordByUnit,
    identifyHazard,
    identifyAllHazard,
    identifyNoChange,
    deleteIdentifyRecord,
    getHazardByOneUnit,
  } from '/@/api/ehs/hazard';
  import { unitViewHazardColumn, getUnitIdentifyRecordColumn } from './hazard.data';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import HazardIndentifyModal from './HazardIndentifyModal.vue';
  import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { Tag, Modal } from 'ant-design-vue';
  import IdentifyResultStatistic from './IdentifyResultStatistic.vue';
  import { getUnitCategory } from '/@/api/ehs/unitCategory';
  import moment from 'moment';
  import UpdateIdentifyRecord from './UpdateIdentifyRecord.vue';
  import HazardInfo from './HazardInfo.vue';
  import IdentifyConfirmModal from './IdentifyConfirmModal.vue';
  export default defineComponent({
    name: 'UnitViewIdentify',
    components: {
      BasicDrawer,
      BasicTable,
      TableAction,
      HazardIndentifyModal,
      PageWrapper,
      IdentifyResultStatistic,
      UpdateIdentifyRecord,
      HazardInfo,
      IdentifyConfirmModal,
      PlusOutlined,
      ExclamationCircleOutlined,
      Tag,
      Modal,
    },
    props: ['mode'],
    emits: ['register', 'success'],
    setup(props, { emit }) {
      const riskLevelOptions = ref('');
      const orgcode = ref('');
      const identifyOptions = ref();
      const tableData = ref({ identitys: [] });
      const ledgerData = ref([]);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const state = reactive({
        searchText: '',
        searchedColumn: '',
      });
      const activeKey = ref('1');
      const unitid = ref();
      const tm = ref([]);
      // 辨识时间周期
      const sortedInfo = ref();
      const filteredInfo = ref();
      // 过滤筛选后显示的数据(表格过滤筛选只会反显,不会更改传入数据)
      const afterFilterData = ref([]);
      const [registerHazardIdentifyInfo, { openModal: openHazardIdentifyInfoModal }] = useModal();
      const [registerHazardLogs, { openModal: openHazardLogsModal }] = useModal();
      const [registerHazardOperate, { openModal: openHazardOperate }] = useModal();
      const [registerUpdateIdentifyRecord, { openModal: openUpdateIdentifyRecordModal }] =
        useModal();
      const searchInput = ref();
      const [registerRecordTable, {}] = useTable({
        canResize: true,
        immediate: true,
        bordered: true,
        ellipsis: true,
        isTreeTable: true,
        showTableSetting: true,
        clickToRowSelect: false,
        tableSetting: {
          redo: false,
        },
        actionColumn: {
          width: 100,
          ifShow: props.mode == 'identify' ? true : false,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        indentSize: 15,
      });
      const [registerLedgerTable, {}] = useTable({
        canResize: true,
        immediate: true,
        bordered: true,
        ellipsis: true,
        isTreeTable: true,
        showTableSetting: true,
        clickToRowSelect: false,
        tableSetting: {
          redo: false,
        },
        actionColumn: {
          width: 100,
          ifShow: props.mode == 'identify' ? true : false,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        indentSize: 15,
      });
      const [register, { closeDrawer, changeLoading }] = useDrawerInner((data) => {
        tableData.value = {
          identifys: [],
        };
        ledgerData.value = [];
        orgcode.value = data.orgcode;
        activeKey.value = '1';
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          unitid.value = data.unitid;
          tm.value = [data.begintm, data.endtm];
          getTableData({
            unitid: data.unitid,
            begintm: data.begintm,
            endtm: data.endtm,
          });
        }
      });
      const handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        state.searchText = selectedKeys[0];
        state.searchedColumn = dataIndex;
      };
      const handleReset = (clearFilters) => {
        clearFilters({ confirm: true });
        state.searchText = '';
      };
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      /**
       * 操作成功后重新请求表格数据
       */
      function opSuccess() {
        let value = {
          unitid: unitid.value,
          begintm: tm.value[0],
          endtm: tm.value[1],
        };
        getTableData(value);
      }
      function onSearch(value) {
        console.log(value);
      }
      // 打开辨识弹窗
      function onIdentifyButtonClick(record, index) {
        let hazardDb = '';
        let propsData: QcUnifyTransToChildProps;
        if (record == null) {
          // 为空是新增,需要传入hazardDb以供查询危险源分类项目及清单
          if (!tableData.value.uccd) {
            createInfoModal({
              title: '提示',
              content: '该单元没有所属单元分类,请先完善单元相关信息',
            });
            return;
          }
          getUnitCategory(tableData.value.uccd).then((res) => {
            propsData = {
              moduleName: '危险源辨识/上报隐患',
              operateString: '填报',
              dataId: null,
              unitid: tableData.value.unitid,
              unitname: tableData.value.unitname,
              index: null,
              hazardDb: res.hdbcd,
              hazardList: ledgerData.value,
            };
            openHazardOperate(true, propsData);
          });
        } else {
          // 重新辨识
          if (index !== null && index !== undefined) {
            console.log(tableData.value, 'tableData');
            propsData = {
              moduleName: '危险源辨识/上报隐患',
              operateString: `填报(当前操作第${index + 1}个,共${afterFilterData.value.length}个)`,
              dataId: record.hazardid,
              unitname: tableData.value.unitname,
              index: index,
              unitid: tableData.value.unitid,
              hazardList: afterFilterData.value,
            };
          } else {
            propsData = {
              moduleName: '危险源辨识/上报隐患',
              operateString: '填报',
              dataId: record.hazardid,
              unitname: record.unitname,
              index: 0,
              unitid: record.unitid,
              hazardList: [],
            };
          }

          openHazardOperate(true, propsData);
        }
        // 传入的导则库清单列表为过滤后的,方便用户操作
        // 用户可以选择 只显示存在,来逐个辨识存在的危险源,就可以暂时忽略不存在的危险源了
      }

      // 重新辨识(全面辨识)
      function reIdentifyButtonClick() {
        Modal.confirm({
          title: '提示',
          icon: createVNode(ExclamationCircleOutlined),
          content:
            '单元的全面辨识使用单元所属分类中设置的危险源清单逐个添加辨识记录，辨识结果自动提取危险源/隐患台账中的最新状态信息，是否确认进行该操作？',
          onOk() {
            identifyAllHazard(unitid.value).then((res) => {
              if (res.success) {
                opSuccess();
                createInfoModal({ title: '提示', content: res.msg });
              } else {
                createErrorModal({ title: '提示', content: res.msg });
              }
            });
          },
        });
      }

      /**
       * 确认无变化
       */
      function onNoChangeButtonClick(record) {
        identifyNoChange(record.hazardid).then((res) => {
          if (res.success) {
            createMessage.success(res.msg);
            opSuccess();
          } else {
            createMessage.error(res.msg);
          }
        });
      }

      function onReportViewButtonClick(record) {}

      function getTableData(param) {
        changeLoading(true);
        // 查询单元的危险源辨识记录
        queryIdentifyRecordByUnit({ ...param, orgcode: orgcode.value })
          .then((res) => {
            // tableData.value = { ...res.items[0].unit, identifys: res.items[0].identifys };
            tableData.value = { identifys: res };
            console.log('queryIdentifyRecordByUnit tableData', tableData.value);
            tableData.value.unitid = unitid.value;
            changeLoading(false);
          })
          .catch((e) => {
            changeLoading(false);
          });
        getHazardByOneUnit({ unitid: unitid.value }).then((res) => {
          ledgerData.value = res?.hazards;
        });
      }

      function tableChange(pagination, filters, sorter, { action, currentDataSource }) {
        console.log(filters, sorter, currentDataSource, 'change');
        afterFilterData.value = currentDataSource;
        unitViewHazardColumn.forEach((item) => {
          if (item.onFilter) item.filteredValue = filters[item.dataIndex];
          if (item.sorter) item.sortOrder = sorter.field == item.dataIndex && sorter.order;
        });
      }

      function onEditRecordButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源辨识/上报隐患',
          operateType: OperationTypeEnum.EDIT,
          operateString: '填报',
          dataId: record.identifyid,
          orgcode: orgcode.value,
        };
        openUpdateIdentifyRecordModal(true, propsData);
      }

      function onDeleteRecordButtonClick(record) {
        deleteIdentifyRecord(record.identifyid).then((res) => {
          if (res.success) {
            createMessage.success(res.msg);
            afterSuccess();
          } else {
            createMessage.error(res.msg);
          }
        });
      }

      /**
       * 查看危险源信息
       */
      function onViewHazardIdentifyButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源辨识/上报隐患',
          operateString: '查看记录',
          dataId: record.identifyid,
        };
        openHazardIdentifyInfoModal(true, propsData);
      }

      watch(
        () => ledgerData.value,
        (newVal) => {
          let data = newVal;
          afterFilterData.value = data;
          unitViewHazardColumn.forEach((item) => {
            if (item.onFilter) item.filteredValue = null;
            if (item.sorter) item.sortOrder = null;
          });
        },
      );
      onMounted(() => {
        queryEnumOptions('EhsRiskLevelEnum,EhsHazardIndentificationResultTypeEnum').then((res2) => {
          // console.log('option res', res);
          if (res2 != undefined && res2 != null && res2.length > 0x0) {
            const riskOp = res2[0].options.map((option) => {
              return {
                value: option.key,
                text: option.value,
                color: option.attribute.split('"')[3],
              };
            });
            const identifyOp = res2[1].options.map((option) => {
              return {
                value: option.key,
                text: option.value,
                color: option.attribute.split('"')[3],
              };
            });
            identifyOptions.value = identifyOp;
            riskLevelOptions.value = riskOp;
            unitViewHazardColumn.filter(
              (item) => item.dataIndex == 'identificationresult',
            )[0].filters = identifyOp;
          }
        });
      });
      return {
        moment,
        unitid,
        orgcode,
        activeKey,
        state,
        tableData,
        afterFilterData,
        ledgerData,
        searchInput,
        tableChange,
        identifyOptions,
        unitViewHazardColumn,
        getUnitIdentifyRecordColumn,
        riskLevelOptions,
        displayModuleTitle,
        registerHazardIdentifyInfo,
        registerHazardLogs,
        registerHazardOperate,
        registerUpdateIdentifyRecord,
        register,
        registerRecordTable,
        registerLedgerTable,
        reIdentifyButtonClick,
        handleSearch,
        handleReset,
        opSuccess,
        onIdentifyButtonClick,
        onReportViewButtonClick,
        onNoChangeButtonClick,
        onEditRecordButtonClick,
        onDeleteRecordButtonClick,
        onViewHazardIdentifyButtonClick,
      };
    },
  });
</script>

<style scoped></style>
